<template>
  <a-card :bordered="false" style="width: 430px; text-align: center">
    <span id="title">添加航班</span>
    <a-form
      :ref="formRef"
      :model="formState"
      :rule="formRules"
      :label-col="{ style: { width: '70px' } }"
    >
      <a-form-item label="航班号" name="number" :rules="formRules.checkBlank">
        <a-input
          v-model:value="formState.number"
          placeholder="请输入航班号（四位）"
        ></a-input>
      </a-form-item>
      <a-form-item label="飞机" name="aircraft">
        <a-cascader
          v-model:value="formState.aircraft"
          placeholder="请选择飞机"
          :options="aircraftOptions"
        ></a-cascader>
      </a-form-item>
      <a-form-item label="地点信息">
        <a-input-group compact>
          <a-cascader
            style="width: 156px"
            :options="options"
            placeholder="起飞地"
            v-model:value="formState.startCity"
          ></a-cascader>
          <a-cascader
            style="width: 156px"
            :options="options"
            placeholder="目的地"
            v-model:value="formState.endCity"
          ></a-cascader>
        </a-input-group>
      </a-form-item>
      <a-form-item label="订票时间" name="bookRange">
        <a-range-picker
          :show-time="{ format: 'HH:mm' }"
          format="YYYY-MM-DD HH:mm"
          :placeholder="['开放订票', '结束订票']"
          :locale="locale"
          v-model:value="formState.bookRange"
          :disabledDate="disabledDate"
        />
      </a-form-item>
      <a-form-item label="飞行时间" name="flyRange">
        <a-range-picker
          :show-time="{ format: 'HH:mm' }"
          format="YYYY-MM-DD HH:mm"
          :placeholder="['预设起飞时间', '预设降落时间']"
          :locale="locale"
          v-model:value="formState.flyRange"
          :disabledDate="disabledDate"
        />
      </a-form-item>
      <a-form-item label="价格" name="price">
        <a-input-number
          v-model:value="formState.price"
          prefix="￥"
          style="width: 312px"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="confirmCreateFlight" :loading="loading"
          >创建航班</a-button
        >
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script lang="ts" setup>
import { FormInstance, message } from "ant-design-vue";
import locale from "ant-design-vue/es/date-picker/locale/zh_CN";
import { Rule } from "ant-design-vue/es/form";
import dayjs, { Dayjs } from "dayjs";
import { onBeforeMount, ref } from "vue";
import { queryAllFormatAircrafts } from "../api/aircraftApi";
import { createFlight, CreateFlightParams } from "../api/flightApi";
import { HTTP_STATUS } from "../api/request";
import options from "../assets/cities";
import { useRequest } from "vue-request";
import emitter from "../utils/mitt";
import { EmitList } from "../utils/emitEnums";

interface FormState extends CreateFlightParams {
  bookRange: [string, string];
  flyRange: [string, string];
  startCity: any;
  endCity: any;
  aircraft: any;
}

onBeforeMount(() => {
  getAircraftList();
  emitter.on(EmitList.AIRCRAFT_CHANGE,() => {
    getAircraftList()
  })
});

const aircraftOptions = ref();

async function getAircraftList() {
  try {
    const res: any = await queryAllFormatAircrafts();
    if (res.status == HTTP_STATUS.SUCCESS) {
      aircraftOptions.value = res.data;
    }
  } catch (error) {
    console.log(error);
  }
}

const { loading, run } = useRequest(createFlight, {
  manual: true,
  onSuccess: () => message.success("创建成功"),
});

function confirmCreateFlight() {
  let data: any = formState.value;

  if (!data.number) {
    message.warn("请输入航班号");
    return;
  } else if (!data.aircraft) {
    message.warn("请选择飞机");
    return;
  } else if (!data.startCity) {
    message.warn("请选择起飞地");
    return;
  } else if (!data.endCity) {
    message.warn("请选择目的地");
    return;
  }
  const deployCity = data.startCity[data.startCity.length - 1];
  const arrivalCity = data.endCity[data.endCity.length - 1];
  if (deployCity == arrivalCity) {
    message.warn("出发地和目的地不能相同");
    return;
  } else if (!data.bookRange) {
    message.warn("请选择订票时间");
    return;
  } else if (!data.flyRange) {
    message.warn("请选择飞行时间");
    return;
  } else if (!data.price) {
    message.warn("请输入价格");
    return;
  } else if (data.price <= 0) {
    message.warn("价格需大于0");
    return;
  }
  data.aircraftId = data.aircraft[1];
  data.deployCity = deployCity;
  data.arrivalCity = arrivalCity;
  data.startTime = data.flyRange[0].format("YYYY-MM-DD HH:mm");
  data.endTime = data.flyRange[1].format("YYYY-MM-DD HH:mm");
  data.startBook = data.bookRange[0].format("YYYY-MM-DD HH:mm");
  data.endBook = data.bookRange[1].format("YYYY-MM-DD HH:mm");
  run(data);

  setTimeout(() => {
    getAircraftList();
    formRef.value?.resetFields();
    emitter.emit(EmitList.FLIGHT_CHANGE)
  }, 2000);
}

const formState = ref<FormState>({} as FormState);
const formRef = ref<FormInstance>();

const disabledDate = (date: Dayjs) => {
  if (date.date() === dayjs().date()) {
    return date.year() < dayjs().year() || date.isAfter(dayjs().add(3, "week"));
  }
  return date.isBefore(dayjs()) || date.isAfter(dayjs().add(3, "week"));
};

const validateBlank = async (_rule: Rule, value: string) => {
  if (value == null || value === "" || /^\s*$/.test(value)) {
    return Promise.reject("请输入值");
  } else if (/\S\s\S/.test(value)) {
    return Promise.reject("不能包含空格");
  }
  return Promise.resolve();
};

const formRules: Record<string, Rule[]> = {
  checkBlank: [
    { validator: validateBlank, trigger: "blur", message: "请输入值！" },
  ],
};
</script>

<style lang="scss" scoped>
#title {
  display: inline-block;
  font-weight: bold;
  margin-bottom: 10px;
}

:deep(.ant-card-body) {
  padding-bottom: 0;
}
</style>
